package com.dd.stack.se.stream.concurrent.reentrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/28 15:11
 * @Description 类功能作用说明
 */
public class TimeoutLockExample {

    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        // t1先获取锁并持有3秒
        new Thread(() -> {
            // 尝试在1秒内获取锁，超时则放弃
            try {
                if (lock.tryLock(1, TimeUnit.SECONDS)) {
                    try {
                        System.out.println(Thread.currentThread().getName() + " 获取锁成功");
                        Thread.sleep(3000); // 模拟长时间任务
                    } finally {
                        lock.unlock();
                    }
                } else {
                    System.out.println(Thread.currentThread().getName() + " 超时未获取到锁");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1").start();
        new Thread(() -> {
            // 尝试在1秒内获取锁，超时则放弃
            try {
                if (lock.tryLock(1, TimeUnit.SECONDS)) {
                    try {
                        System.out.println(Thread.currentThread().getName() + " 获取锁成功");
                        Thread.sleep(3000); // 模拟长时间任务
                    } finally {
                        lock.unlock();
                    }
                } else {
                    System.out.println(Thread.currentThread().getName() + " 超时未获取到锁");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t2").start();
        // t2尝试获取锁，1秒后超时
    }
}
